package in.abip.kazumi;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SettingsActivity extends Activity {
	
	public static final String SETTINGS = "Settings";
	public static final String HARDWARE_IP = "HardwareIp";
	public static final String HARDWARE_PORT = "HardwarePort";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_activity);
		_bindCancel();
		_readSettings();
		_bindApply();
	}

	private void _bindCancel() {
		Button button = (Button) findViewById(R.id.cancel);
		button.setOnClickListener(
			new OnClickListener() {
				public void onClick(View v) {
					SettingsActivity.this.finish();
				}
			}
		);
	}
	
	protected void _bindApply() {
		Button button = (Button) findViewById(R.id.apply);
		button.setOnClickListener(
			new OnClickListener() {
				public void onClick(View v) {
					_writeSettings();
					SettingsActivity.this.finish();
				}
			}
		);
	}
	
	private void _readSettings() {
		SharedPreferences pref = getSharedPreferences(
			SETTINGS,
			Context.MODE_PRIVATE
		);
		EditText text = null;
		if (pref.contains(HARDWARE_IP)) {
			text = (EditText) findViewById(R.id.ip);
			text.setText(pref.getString(
				HARDWARE_IP,
				"192.168.0.1")
			);
		}
		if (pref.contains(HARDWARE_PORT)) {
			text = (EditText) findViewById(R.id.port);
			String value = "";
			value = Integer.toString(pref.getInt( HARDWARE_PORT, 80));
			text.setText(value);
		}
	}
	
	private void _writeSettings() {
		EditText text = null;
		SharedPreferences pref = getSharedPreferences(
			SETTINGS,
			Context.MODE_PRIVATE
		);
		Editor editor = pref.edit();
		text = (EditText) findViewById(R.id.ip);
		editor.putString(HARDWARE_IP, text.getText().toString());
		editor.commit();
		text = (EditText) findViewById(R.id.port);
		int value = 80;
		value = Integer.parseInt(text.getText().toString());
		editor.putInt(HARDWARE_PORT, value);
		editor.commit();
	}
}
